import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**军团管理器属性枚举*/
export const enum E_LegionManager {
	/** 加入的军团id*/
	LEGION_ID = 0,
	/** 军团列表*/
	LEGIONS = 1,
	/** 总贡献*/
	TOTAL_CONTRIBUTION = 2,
	/** 本周贡献*/
	WEEK_CONTRIBUTION = 3,
	/** 本周贡献重置时间*/
	WEEK_CONTRIBUTION_TIME = 4,
	/**<configId, 数量> 今日购买过的数量*/
	BUY_ITEM_NUMS = 5,
	/**<捐献类型, 贡献次数> 贡献次数*/
	DONATE_CONTRIBUTION = 6,
	/**上次捐献时间*/
	LAST_DONATE_TIME = 7,
	/** 上次购买物品时间*/
	LAST_BUY_ITEM_TIME = 8,
	/**枚举数量*/
	EnumCount = 9
}


/**军团管理器*/
export class LegionManager {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_LEGION_MANAGER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_LEGION_MANAGER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: LegionManager[] = [];

	/**创建入口*/
	public static create(json?: string): LegionManager {
		const c = this.POOL.pop() || new LegionManager();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/** 加入的军团id (int32)*/
	protected _legionId: number;
	/** 军团列表 (uint32)*/
	protected _legions: number[] = [];
	/** 总贡献 (uint32)*/
	protected _totalContribution: number;
	/** 本周贡献 (uint32)*/
	protected _weekContribution: number;
	/** 本周贡献重置时间 (uint32)*/
	protected _weekContributionTime: number;
	/**<configId, 数量> 今日购买过的数量 (uint32, uint32)*/
	protected _buyItemNums: HashMap<number, number> = null;
	/**<捐献类型, 贡献次数> 贡献次数 (uint32, uint32)*/
	protected _donateContribution: HashMap<number, number> = null;
	/**上次捐献时间 (uint32)*/
	protected _lastDonateTime: number;
	/** 上次购买物品时间 (uint32)*/
	protected _lastBuyItemTime: number;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (LegionManager.POOL.indexOf(this) === -1) {
			LegionManager.POOL.push(this);
		}
	}

	/** 加入的军团id*/
	public get legionId() {
		return this._legionId;
	}


	/** 加入的军团id*/
	public set legionId(v: number) {
		this._legionId = v;
	}


	/**增加 军团列表*/
	public addLegions(v: number): void {
		if (this._legions.indexOf(v) === -1) {
			this._legions.push(v);
		}
	}

	/**删除 军团列表*/
	public removeLegions(v: number): void {
		const idx = this._legions.indexOf(v);
		if (idx >= 0) {
			this._legions.splice(idx, 1);
		}
	}

	/**获取 军团列表列表*/
	public getLegionsList(): number[] {
		return this._legions;
	}

	/** 总贡献*/
	public get totalContribution() {
		return this._totalContribution;
	}


	/** 总贡献*/
	public set totalContribution(v: number) {
		this._totalContribution = v;
	}


	/** 本周贡献*/
	public get weekContribution() {
		return this._weekContribution;
	}


	/** 本周贡献*/
	public set weekContribution(v: number) {
		this._weekContribution = v;
	}


	/** 本周贡献重置时间*/
	public get weekContributionTime() {
		return this._weekContributionTime;
	}


	/** 本周贡献重置时间*/
	public set weekContributionTime(v: number) {
		this._weekContributionTime = v;
	}


	/**设置<configId, 数量> 今日购买过的数量*/
	public putBuyItemNums(k: number, v: number): number {
		const ov = this._buyItemNums.put(k, v);
		return ov || 0;
	}


	/**获取<configId, 数量> 今日购买过的数量*/
	public getBuyItemNums(k: number) {
		return this._buyItemNums.get(k) || 0;
	}


	/**删除<configId, 数量> 今日购买过的数量*/
	public removeBuyItemNums(k: number): number {
		const ov = this._buyItemNums.remove(k);
		return ov || 0;
	}


	/**获取<configId, 数量> 今日购买过的数量映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getBuyItemNumsKeys(): number[] {
		return this._buyItemNums.getKeys();
	}


	/**获取<configId, 数量> 今日购买过的数量映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getBuyItemNumsValues(): number[] {
		return this._buyItemNums.getValues();
	}


	/**清空<configId, 数量> 今日购买过的数量映射表*/
	public clearBuyItemNumsMap(): void {
		this._buyItemNums.clear();
	}


	/**设置<捐献类型, 贡献次数> 贡献次数*/
	public putDonateContribution(k: number, v: number): number {
		const ov = this._donateContribution.put(k, v);
		return ov || 0;
	}


	/**获取<捐献类型, 贡献次数> 贡献次数*/
	public getDonateContribution(k: number) {
		return this._donateContribution.get(k) || 0;
	}


	/**删除<捐献类型, 贡献次数> 贡献次数*/
	public removeDonateContribution(k: number): number {
		const ov = this._donateContribution.remove(k);
		return ov || 0;
	}


	/**获取<捐献类型, 贡献次数> 贡献次数映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getDonateContributionKeys(): number[] {
		return this._donateContribution.getKeys();
	}


	/**获取<捐献类型, 贡献次数> 贡献次数映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getDonateContributionValues(): number[] {
		return this._donateContribution.getValues();
	}


	/**清空<捐献类型, 贡献次数> 贡献次数映射表*/
	public clearDonateContributionMap(): void {
		this._donateContribution.clear();
	}


	/**上次捐献时间*/
	public get lastDonateTime() {
		return this._lastDonateTime;
	}


	/**上次捐献时间*/
	public set lastDonateTime(v: number) {
		this._lastDonateTime = v;
	}


	/** 上次购买物品时间*/
	public get lastBuyItemTime() {
		return this._lastBuyItemTime;
	}


	/** 上次购买物品时间*/
	public set lastBuyItemTime(v: number) {
		this._lastBuyItemTime = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_LegionManager): any {
		switch (k) {
			case E_LegionManager.LEGION_ID: return this._legionId;
			case E_LegionManager.LEGIONS: return this._legions;
			case E_LegionManager.TOTAL_CONTRIBUTION: return this._totalContribution;
			case E_LegionManager.WEEK_CONTRIBUTION: return this._weekContribution;
			case E_LegionManager.WEEK_CONTRIBUTION_TIME: return this._weekContributionTime;
			case E_LegionManager.BUY_ITEM_NUMS: return this._buyItemNums;
			case E_LegionManager.DONATE_CONTRIBUTION: return this._donateContribution;
			case E_LegionManager.LAST_DONATE_TIME: return this._lastDonateTime;
			case E_LegionManager.LAST_BUY_ITEM_TIME: return this._lastBuyItemTime;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_LegionManager, v: any): void {
		switch (k) {
			case E_LegionManager.LEGION_ID: this._legionId = v; break;
			case E_LegionManager.LEGIONS: this._legions = v; break;
			case E_LegionManager.TOTAL_CONTRIBUTION: this._totalContribution = v; break;
			case E_LegionManager.WEEK_CONTRIBUTION: this._weekContribution = v; break;
			case E_LegionManager.WEEK_CONTRIBUTION_TIME: this._weekContributionTime = v; break;
			case E_LegionManager.BUY_ITEM_NUMS: this._buyItemNums = v; break;
			case E_LegionManager.DONATE_CONTRIBUTION: this._donateContribution = v; break;
			case E_LegionManager.LAST_DONATE_TIME: this._lastDonateTime = v; break;
			case E_LegionManager.LAST_BUY_ITEM_TIME: this._lastBuyItemTime = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		// 加入的军团id
		this._legionId = 0;
		// 军团列表
		if (this._legions) {
			this._legions.length = 0;
		}
		else {
			this._legions = [];
		}
		// 总贡献
		this._totalContribution = 0;
		// 本周贡献
		this._weekContribution = 0;
		// 本周贡献重置时间
		this._weekContributionTime = 0;
		//<configId, 数量> 今日购买过的数量
		if (this._buyItemNums) {
			this._buyItemNums.clear();
		}
		else {
			this._buyItemNums = new HashMap<number, number>();
		}
		//<捐献类型, 贡献次数> 贡献次数
		if (this._donateContribution) {
			this._donateContribution.clear();
		}
		else {
			this._donateContribution = new HashMap<number, number>();
		}
		//上次捐献时间
		this._lastDonateTime = 0;
		// 上次购买物品时间
		this._lastBuyItemTime = 0;
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._legionId) {
			json.legionId = this._legionId;
		}
		if (this._legions) {
			json.legions = this._legions;
		}
		if (this._totalContribution) {
			json.totalContribution = this._totalContribution;
		}
		if (this._weekContribution) {
			json.weekContribution = this._weekContribution;
		}
		if (this._weekContributionTime) {
			json.weekContributionTime = this._weekContributionTime;
		}
		if (this._buyItemNums.size() > 0) {
			const ks = this._buyItemNums.getKeys();
			const vs = this._buyItemNums.getValues();
			json.buyItemNums = [ks, vs];
		}
		if (this._donateContribution.size() > 0) {
			const ks = this._donateContribution.getKeys();
			const vs = this._donateContribution.getValues();
			json.donateContribution = [ks, vs];
		}
		if (this._lastDonateTime) {
			json.lastDonateTime = this._lastDonateTime;
		}
		if (this._lastBuyItemTime) {
			json.lastBuyItemTime = this._lastBuyItemTime;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.legionId) {
			this._legionId = json.legionId;
		}
		if (json.legions) {
			this._legions = json.legions;
		}
		if (json.totalContribution) {
			this._totalContribution = json.totalContribution;
		}
		if (json.weekContribution) {
			this._weekContribution = json.weekContribution;
		}
		if (json.weekContributionTime) {
			this._weekContributionTime = json.weekContributionTime;
		}
		if (json.buyItemNums) {
			const ks: number[] = json.buyItemNums[0];
			const vs: number[] = json.buyItemNums[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._buyItemNums.setKeyAndValueList(ks, vs);
			}
			else if (json.buyItemNums.getKeys && json.buyItemNums.getValues) {	//结构体
				const ks2 = json.buyItemNums.getKeys();
				const vs2 = json.buyItemNums.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._buyItemNums.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		if (json.donateContribution) {
			const ks: number[] = json.donateContribution[0];
			const vs: number[] = json.donateContribution[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._donateContribution.setKeyAndValueList(ks, vs);
			}
			else if (json.donateContribution.getKeys && json.donateContribution.getValues) {	//结构体
				const ks2 = json.donateContribution.getKeys();
				const vs2 = json.donateContribution.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._donateContribution.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		if (json.lastDonateTime) {
			this._lastDonateTime = json.lastDonateTime;
		}
		if (json.lastBuyItemTime) {
			this._lastBuyItemTime = json.lastBuyItemTime;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeInt32(this._legionId);
		// 军团列表
		{
			const list = this._legions;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					byte.writeUint32(list[i]);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
		byte.writeUint32(this._totalContribution);
		byte.writeUint32(this._weekContribution);
		byte.writeUint32(this._weekContributionTime);
		//<configId, 数量> 今日购买过的数量
		{
			const ks = this._buyItemNums.getKeys();
			const vs = this._buyItemNums.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				byte.writeUint32(vs[i]);
			}
		}
		//<捐献类型, 贡献次数> 贡献次数
		{
			const ks = this._donateContribution.getKeys();
			const vs = this._donateContribution.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				byte.writeUint32(vs[i]);
			}
		}
		byte.writeUint32(this._lastDonateTime);
		byte.writeUint32(this._lastBuyItemTime);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._legionId = byte.readInt32();
		// 军团列表
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				this._legions[i] = byte.readUint32();
			}
		}
		this._totalContribution = byte.readUint32();
		this._weekContribution = byte.readUint32();
		this._weekContributionTime = byte.readUint32();
		//<configId, 数量> 今日购买过的数量
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = byte.readUint32();
				this._buyItemNums.put(k, v);
			}
		}
		//<捐献类型, 贡献次数> 贡献次数
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = byte.readUint32();
				this._donateContribution.put(k, v);
			}
		}
		this._lastDonateTime = byte.readUint32();
		this._lastBuyItemTime = byte.readUint32();
		return this;
	}


	/**克隆*/
	public clone(): LegionManager {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = LegionManager.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = LegionManager.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			// 加入的军团id
			if (idx === E_LegionManager.LEGION_ID) {
				const oldv = this._legionId;
				this._legionId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._legionId, oldv);
				i += 2;
				continue;
			}
			// 军团列表
			if (idx === E_LegionManager.LEGIONS) {
				const c: number = us[i + 1];
				const v: number = us[i + 2];
				if (c === 0) {
					const idx = this._legions.indexOf(v);
					if (idx >= 0) {
						this._legions.splice(idx, 1);
					}
				}
				else {
					const idx = this._legions.indexOf(v);
					if (idx === -1) {
						this._legions.push(v);
					}
				}
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}
			// 总贡献
			if (idx === E_LegionManager.TOTAL_CONTRIBUTION) {
				const oldv = this._totalContribution;
				this._totalContribution = us[i + 1];
				IAsync.dispatch(eventID, idx, this._totalContribution, oldv);
				i += 2;
				continue;
			}
			// 本周贡献
			if (idx === E_LegionManager.WEEK_CONTRIBUTION) {
				const oldv = this._weekContribution;
				this._weekContribution = us[i + 1];
				IAsync.dispatch(eventID, idx, this._weekContribution, oldv);
				i += 2;
				continue;
			}
			// 本周贡献重置时间
			if (idx === E_LegionManager.WEEK_CONTRIBUTION_TIME) {
				const oldv = this._weekContributionTime;
				this._weekContributionTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._weekContributionTime, oldv);
				i += 2;
				continue;
			}

			//<configId, 数量> 今日购买过的数量
			if (idx === E_LegionManager.BUY_ITEM_NUMS) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putBuyItemNums(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			//<捐献类型, 贡献次数> 贡献次数
			if (idx === E_LegionManager.DONATE_CONTRIBUTION) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putDonateContribution(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}
			//上次捐献时间
			if (idx === E_LegionManager.LAST_DONATE_TIME) {
				const oldv = this._lastDonateTime;
				this._lastDonateTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._lastDonateTime, oldv);
				i += 2;
				continue;
			}
			// 上次购买物品时间
			if (idx === E_LegionManager.LAST_BUY_ITEM_TIME) {
				const oldv = this._lastBuyItemTime;
				this._lastBuyItemTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._lastBuyItemTime, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in LegionManager with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: LegionManager): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._legionId !== other._legionId) {
			updates.push(E_LegionManager.LEGION_ID, this._legionId);
		}

		// 军团列表
		{
			const idx = E_LegionManager.LEGIONS;
			const rs = MathUtils.intersectSortedArray(this._legions, other._legions);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv);
				}
			}
		}
		if (this._totalContribution !== other._totalContribution) {
			updates.push(E_LegionManager.TOTAL_CONTRIBUTION, this._totalContribution);
		}
		if (this._weekContribution !== other._weekContribution) {
			updates.push(E_LegionManager.WEEK_CONTRIBUTION, this._weekContribution);
		}
		if (this._weekContributionTime !== other._weekContributionTime) {
			updates.push(E_LegionManager.WEEK_CONTRIBUTION_TIME, this._weekContributionTime);
		}

		//<configId, 数量> 今日购买过的数量
		{
			const idx = E_LegionManager.BUY_ITEM_NUMS;
			const ks1 = this._buyItemNums.getKeys();
			const ks2 = other._buyItemNums.getKeys();
			const vs1 = this._buyItemNums.getValues();
			const vs2 = other._buyItemNums.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getBuyItemNums(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getBuyItemNums(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//<捐献类型, 贡献次数> 贡献次数
		{
			const idx = E_LegionManager.DONATE_CONTRIBUTION;
			const ks1 = this._donateContribution.getKeys();
			const ks2 = other._donateContribution.getKeys();
			const vs1 = this._donateContribution.getValues();
			const vs2 = other._donateContribution.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getDonateContribution(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getDonateContribution(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}
		if (this._lastDonateTime !== other._lastDonateTime) {
			updates.push(E_LegionManager.LAST_DONATE_TIME, this._lastDonateTime);
		}
		if (this._lastBuyItemTime !== other._lastBuyItemTime) {
			updates.push(E_LegionManager.LAST_BUY_ITEM_TIME, this._lastBuyItemTime);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(LegionManager.TOTAL_EVENT_ID, this.getV(0));
	}

}
